// 缓存解码后的音频数据
const audioBufferCache = new Map();
const allDrawParams = []
const durationPerBar = 0.05

function drawAudioWave(audio, startTime, endTime, callback) {
  allDrawParams.length = 0
  let canvasW = 200
  canvasW = (canvasW * (endTime - startTime)) / 5
  const canvasH = 24
  // 创建一个canvasW*canvasH的画布，背景透明
  const canvas = document.createElement('canvas')
  canvas.width = canvasW
  canvas.height = canvasH
  const ctx = canvas.getContext('2d')

  // 提取音频，绘制频谱，每0.2秒绘制一个柱子，黄色每个柱子的宽度为canvasW/((endTime - startTime)/0.2)
  // 创建离屏AudioContext来处理音频
  const audioContext = new (window.AudioContext || window.webkitAudioContext)()
  
  // 检查是否有缓存的audioBuffer
  const audioSrc = audio.src
  if (audioBufferCache.has(audioSrc)) {
    // 使用缓存的数据
    processAudioData(audioContext, audioBufferCache.get(audioSrc), startTime, endTime, canvas, ctx, callback)
  } else {
    // 将audio对象转换为ArrayBuffer
    fetch(audioSrc)
      .then((response) => response.arrayBuffer())
      .then((arrayBuffer) => audioContext.decodeAudioData(arrayBuffer))
      .then((audioBuffer) => {
        // 缓存解码后的数据
        audioBufferCache.set(audioSrc, audioBuffer)
        processAudioData(audioContext, audioBuffer, startTime, endTime, canvas, ctx, callback)
      })
      .catch((error) => {
        console.error('Error drawing waveform:', error)
        // 出错时设为空图像或默认图像
        callback(null)
      })
  }
}

function processAudioData(audioContext, audioBuffer, startTime, endTime, canvas, ctx, callback) {
  // 获取左声道数据
  const rawData = audioBuffer.getChannelData(0)

  // 计算采样率和时间范围
  const sampleRate = audioBuffer.sampleRate
  const startSample = Math.floor(startTime * sampleRate)
  const endSample = Math.floor(endTime * sampleRate)
  const segmentData = rawData.slice(startSample, endSample)

  // 计算柱子数量和每个柱子的样本数
  const duration = endTime - startTime
  const barCount = Math.floor(duration / durationPerBar) // 每durationPerBar秒一个柱子
  const barWidth = Math.min(canvas.width / barCount, 4)
  const samplesPerBar = Math.floor(segmentData.length / barCount)

  // 绘制柱状图
  ctx.fillStyle = 'green'
  for (let i = 0; i < barCount; i++) {
    // 计算每个柱子的最大振幅
    let maxAmplitude = 0
    const startIndex = i * samplesPerBar
    const endIndex = Math.min(
      startIndex + samplesPerBar,
      segmentData.length
    )

    for (let j = startIndex; j < endIndex; j++) {
      const amplitude = Math.abs(segmentData[j])
      if (amplitude > maxAmplitude) {
        maxAmplitude = amplitude
      }
    }

    // 计算柱子高度（基于最大振幅）
    const barHeight = Math.max(maxAmplitude * canvas.height, 1)

    // 绘制柱子
    // ctx.fillRect(
    //   i * barWidth,
    //   (canvasH - barHeight) / 2,
    //   barWidth - 1,
    //   barHeight
    // )
    drawBar(
      ctx,
      i * barWidth,
      (canvas.height - barHeight) / 2,
      barWidth - 1,
      barHeight
    )
  }
  drawByInterval(canvas, duration,callback)
}

function drawByInterval(canvas,duration, callback) {
  if (allDrawParams.length > 0) {
    const { ctx, x, y, width, height } = allDrawParams.shift()
    ctx.fillRect(x, y, width, height)
    drawByInterval(canvas,duration, callback)
  }
  else{    
    // 获取class=[sentence-pair active]中的class=“sentence-item english”中的class="text"的dom，设置animation
    const sentencePair = document.querySelector('.sentence-pair.active')
    if (sentencePair) {
      const sentenceItem = sentencePair.querySelector('.sentence-item.english')
      if (sentenceItem) {
        const text = sentenceItem.querySelector('.text')
        const w = text.offsetWidth;
        const canvasW = canvas.width;
        // 设置全局的样式变量--waveform-width=w+canvasW
        document.documentElement.style.setProperty('--waveform-width', `${w + canvasW}px`);
        document.documentElement.style.setProperty('--waveform-duration', `${duration*0.8}s`);
      }
    }
    callback(canvas.toDataURL());
  }
}

function drawBar(ctx, x, y, width, height) {
  allDrawParams.push({ ctx, x, y, width, height })
}

export default drawAudioWave